<template>
     <el-form ref="formRef" :model="formDate" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
            <el-form-item label="类目名称" prop="name">
                <el-input v-model="formDate.name" />
            </el-form-item>
            <el-form-item label="图片" prop="img" >
                <el-input v-model="formDate.img"/>
            </el-form-item>
            <el-form-item label="排序" prop="price">
                <el-input-number v-model="formDate.price" :min="1" :max="10" />
            </el-form-item>
             <el-form-item label="价格" prop="seq">
              
                    <el-input-number v-model="formDate.seq" :precision="2" :step="0.1" />
                </el-form-item>
            <el-form-item label="类目">
                     <el-input v-model.number="formDate.categoryId" />
            </el-form-item>
             <el-form-item label="介绍">
                     <el-input v-model="formDate.brief" />
                </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(formRef)">添加</el-button>
                <el-button @click="resetForm(formRef)">重置</el-button>
            </el-form-item>
        </el-form>
</template>
<script setup>
import { onMounted, reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { insert } from '@/api/productApi'
import { useRouter } from 'vue-router';
const router = useRouter()
const formRef = ref()

//正则描述  表单验证里面的内容粘贴过来
const rules = reactive({
    name: [
        { required: true, message: '分类名称必填', trigger: 'blur' },
    ]
})
const formDate = reactive({
    name: '',
    img: '',
    seq: 0,
    price: 0,
    brief: '请输入商品简介',
    categoryId: 0,
})

const formSubmit = () => {
    insert({
        name: formDate.name, img: formDate.img, seq: formDate.seq, categoryId: formDate.categoryId,
        price: formDate.price, brief: formDate.brief
    }).then(res => { 
        console.log(res);
        ElMessage.success("新增成功")
        router.push({'name':'product-list'})
    })
 }

const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
             formSubmit()
        } else {
            console.log('error submit!', fields)
        }
    })
}
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}

</script>